<?php


namespace Composite;


class Client
{
    public static function main()
    {
        $root = new Composite();
        $root->add(new Composite());

        $composite = new Composite();
        $composite->add(new Leaf('A'));
        $composite->add(new Leaf('B'));
        $root->add($composite);

        $root->operation();
    }
}


interface Component
{
    public function add(Component $component): void;

    public function remove(Component $component): void;

    public function getChild(int $i): Component;

    public function operation(): void;
}

class Leaf implements Component
{
    protected string $name = '';

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function add(Component $component): void
    {
    }

    public function remove(Component $component): void
    {
    }

    public function getChild(int $i): Component
    {
        return null;
    }

    public function operation(): void
    {
        echo '叶子结点:', $this->name, '被访问.', PHP_EOL;
    }
}

class Composite implements Component
{
    /**
     * @var Component[] $children
     */
    protected array $children = [];

    public function add(Component $component): void
    {
        $this->children[] = $component;
    }

    public function remove(Component $component): void
    {
        $index = array_search($component, $this->children, true);
        if (false !== $index) {
            array_splice($this->children, $index, 1);
        }
    }

    public function getChild(int $i): Component
    {
        return $this->children[$i];
    }

    public function operation(): void
    {
        foreach ($this->children as $child) {
            $child->operation();
        }
    }
}


Client::main();

